const crypto = require('crypto');
const userService = require('../services/user.service');
const jwt = require('jsonwebtoken');
const SECRETE_KEY = require('../keys/jwt-key');
const connectionPoll = require('../app/mysql');
//进行密码加密的中间件
const md5Password = async (ctx, next) => {
    //使用MD5进行加密
    const hash = crypto.createHash('md5');
    hash.update(ctx.request.body.password);
    const md5Password =  hash.digest('hex');
    ctx.request.body.password = md5Password;
    await next();   
}

//直接加密密码的算法
const md5ByPassword = (password)=>
{
   //使用MD5进行加密
    const hash = crypto.createHash('md5');
    hash.update(password);
    const md5Password =  hash.digest('hex');
    return md5Password;
}

//验证登录用户是否合法的中间件
const verifyLogin = async (ctx, next) => {
    const { name, password } = ctx.request.body;
    //验证用户名是否存在
    const res = await userService.findName(name);
    if (res.length === 0)
    {
        ctx.body = {
            code: 10002,
            message:"用户不存在,请先注册"
        }    
        return;
    }
    
    //验证用户密码是否正确
    const pwd = await userService.findPassword(name);
    const md5Pwd = md5ByPassword(password);
    //查找密码进行来校对
    if (md5Pwd !== pwd.password)
    {
        ctx.body = {
            code: 1001,
            message:"用户名或者密码错误"
        }
        return;
    }
    
    //保存user,执行下一个中间件
    const statement = "select id from t_user where name = ?";
    const [val] = await connectionPoll.promise().execute(statement, [name]);
    console.log("id:", val);
    ctx.user = {
        name,
        password,
        id:val[0].id
    }
    await next();
}

const  verifyToken = async (ctx, next) => {
     //先获取token
        let token = ctx.request.headers.authorization;
        token  = token.replace('Bearer ', '');
        console.log(token);
        //验证token是否是正确的
    try {
            
            const result = jwt.verify(token, SECRETE_KEY);
           //保存好id和name信息往下传递
           console.log("result:", result);
            ctx.user = { id: result.id, name: result.name };
            ctx.body = "验证通过~";
        } catch (err)
        {
            return ctx.body = "无效的token~";
    }
    
    await next();
}

//验证权限
const verifyPermission = async(ctx, next) =>
{
    const { id } = ctx.params;
    const user_id = ctx.user.id;
    //查找
    const statement = "select content from t_moment where id = ? and user_id = ?";
    const [result] = await connectionPoll.promise().execute(statement, [id, user_id]);
     
    //返回
    if (!result.length)
    {
        return ctx.body = {
           message:"没有操作该评论的权限"
       }    
    }

    await next();
}




module.exports = {
    md5Password,
    verifyLogin,
    verifyToken,
    verifyPermission
}